#include "reporttask.h"
#include <QDebug>

ReportTask::ReportTask(QNetworkAccessManager *m, QString addr, QString repFilePath, QObject *parent): QObject(parent)
{
    manager = m;
    taskFlag = false;
    nUrl = addr;
    reportPath = repFilePath;
}

ReportTask::~ReportTask()
{
    emit reportRst(taskFlag);
    qDebug()<<"[report send over]:"<<reportPath;
}

void ReportTask::taskStart()
{
    QFile f(reportPath);
    if(!f.exists())
        return;
    if(!f.open(QFile::ReadOnly))
        return;

    QByteArray src_sign = f.read(16);
    QByteArray qba = f.readAll();
    QByteArray sign = QCryptographicHash::hash(qba+QByteArray("hnrmxx")+f.fileName().toLocal8Bit(), QCryptographicHash::Md5);
    if(src_sign != sign)
    {
        qWarning("report sign wrong.");
        this->deleteLater();
        return;
    }
    qDebug()<<"[report]"<<nUrl<<"\n"<<qba;//QString::fromUtf8(qba);
//    return;
    QNetworkRequest request;
    request.setRawHeader("Content-Type", "application/x-www-form-urlencoded");//"application/soap+xml;charset=utf-8");//"application/x-www-form-urlencoded"
    request.setRawHeader("X-Requested-With","XMLHttpRequest");
    request.setUrl(nUrl);
//    if(reply != NULL)
//    {
//        reply->deleteLater();
//    }
    reply = manager->post(request, qba);
    connect(reply, SIGNAL(readyRead()), this, SLOT(recvGoodsReport()));
    QTimer::singleShot(10000, this, SLOT(sendTimeOut()));
}

void ReportTask::taskFinish()
{
    QFile f(reportPath);
    if(f.exists())
        f.remove();
    this->deleteLater();
}

void ReportTask::readXmlRst(QByteArray rst)
{
    QXmlStreamReader reader(rst);
    QString code = "-1";
//    QString msg = QString();

    while(!reader.atEnd())
    {
        if(reader.isStartElement())
        {
            if(reader.name() == QString("code"))
            {
                reader.readNext();
                code = reader.text().toString();
                qDebug()<<"[code]:"<<code;
            }
//            else if(reader.name() == QString("define"))
//            {
//                reader.readNext();
//                qDebug()<<"[define]"<<reader.text();
//            }
        }
        reader.readNext();
    }

    if(code == "0")
    {
        taskFlag = true;
        qDebug()<<"[report]"<<reportPath<<"send success.";
        taskFinish();
    }
    else
    {
        taskFlag = false;
        qDebug()<<"[report]"<<reportPath<<"send failed.";
    }
}

void ReportTask::recvGoodsReport()
{
    QByteArray qba = reply->readAll();
    qDebug()<<QString(qba);
    readXmlRst(qba);
    reply->deleteLater();
    reply = NULL;
}

void ReportTask::sendTimeOut()
{
    this->deleteLater();
}
